const db = require("../db/index");

// 获取全部消息
exports.getuserMessage = (req, res) => {
  const sql =
    "select message.*,articles.title,articles.content,user.username as foundername,user.face as founderface from message,user,articles where message.toUserid = ? and user.id = message.founderid and articles.id = message.articleid  order by message.createdate desc";
  db.query(sql, req.user.id, (err, result1) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    const sql2 =
      "update message set isread = 1 where message.toUserid = ?";
    db.query(sql2, req.user.id, (err) => {
      if (err)
        return res.send({
          code: 500,
          message: "数据库异常" + err.message,
        });
      return res.send({
        code: 200,
        message: "获取消息成功",
        data: result1.filter((item) => item.founderid != item.toUserid)
      });
    });
  });
};
//获取未读消息条数
exports.getuserMessageLength = (req, res) => {
  const sql =
    "select message.* from message where message.toUserid = ? and message.isread = 0";
  db.query(sql, req.user.id, (err, result1) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    return res.send({
      code: 200,
      message: "获取消息成功",
      count: result1.filter((item) => item.founderid != item.toUserid).length
    });
  });
};
//获取我的收藏夹内容
exports.getmycollect = (req,res)=>{
  const sql = 'select collects.*,collects.articleid,collects.authorid,articles.title,articles.content,articles.viewcount,articles.firstpub,user.username as authorname,storefiles.storeid,storehouse.storename,user.face from collects,user,articles,storehouse,storefiles where collects.collectorsid = ? and collects.status = 1 and user.id = collects.authorid and articles.id = collects.articleid and storefiles.typeid = collects.articleid and storefiles.type = 1 and storehouse.id = storefiles.storeid order by collects.createdate desc'
  db.query(sql,req.user.id,(err,result)=>{
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
      let params = [];
      for (let i = 0; i < result.length; i++) {
        params[i] = {
          id: result[i].articleid,
          title: result[i].title,
          content: result[i].content,
          store: {
            id: result[i].storeid,
            name: result[i].storename,
          },
          author: {
            id: result[i].authorid,
            username: result[i].authorname,
            face: result[i].face,
          },
          StarDate:result[i].createdate,
          viewcount: result[i].viewcount,
          first_pub: result[i].firstpub,
        };
      }
      return res.send({
        code:200,
        message:'获取收藏夹成功',
        data:params
      })
  })
}
